from PyQt5.QtWidgets import QApplication, QAction, QFileDialog, QTextEdit
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from os import chmod
import stat

class OpenFile(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('文件系统')
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

        self.statusBar()
        self.setFocus()

        openFile = QAction('打开', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('打开文件')
        openFile.triggered.connect(self.showDialog)

        saveOtherPath = QAction('另存为', self)
        saveOtherPath.setShortcut('Ctrl+S')
        saveOtherPath.setStatusTip('另存为')
        saveOtherPath.triggered.connect(self.showOtherPath)

        runAuthor = QAction('拥有者执行权限', self)
        runAuthor.setStatusTip('拥有者执行权限')
        runAuthor.triggered.connect(lambda: self.changeAuthorization(1))

        writeAuthor = QAction('拥有者写权限', self)
        writeAuthor.setStatusTip('拥有者写权限')
        writeAuthor.triggered.connect(lambda: self.changeAuthorization(2))

        # 菜单条
        menubar = self.menuBar()
        file = menubar.addMenu('&文件')
        file.addAction(openFile)

        save = menubar.addMenu('&另存为')
        save.addAction(saveOtherPath)

        author = menubar.addMenu('&权限设置')
        author.addAction(runAuthor)
        author.addAction(writeAuthor)


        self.filename = ""
        self.data = ""

    def showDialog(self):
        self.filename, _ = QFileDialog.getOpenFileName(self, 'Open file', './')
        if self.filename:
            print(self.filename)
            file = open(self.filename)
            self.data = file.read()
            self.textEdit.setText(self.data)

    def showOtherPath(self):
        if self.filename:
            # 获取到另存为的路径地址
            fileNameOtherPath, _= QFileDialog.getSaveFileName(self, "另存为", "./{}".format(self.filename), "All Files (*);;Text Files (*.txt)")
            # 写入文件
            with open(fileNameOtherPath, 'w') as f:
                f.write(self.textEdit.toPlainText())
            self.textEdit.setText("<另存为>成功")

        else:
            self.textEdit.setText("请先选择文件，再进行<另存为>操作")

    def changeAuthorization(self, n):
        if self.filename:
            if n == 1:
                chmod(self.filename, stat.S_IXUSR)
                self.textEdit.setText('拥有者具有执行权限')
            elif n == 2:
                chmod(self.filename, stat.S_IWUSR)
                self.textEdit.setText('拥有者具有写权限')
        else:
            self.textEdit.setText("请先选择文件，再进行<权限设置>操作")

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    qb = OpenFile()
    qb.show()
    sys.exit(app.exec_())